<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.List"%>
<%@ page import="com.google.appengine.api.datastore.*"%>
<%@ page import="com.google.appengine.api.memcache.*"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Praktikaportaal | Tere Tulemast</title>
</head>
<body>
	<%@ include file="header.jsp"%>
	<div id="content">
		<div class="content-container">
			<%
				// Warm cache.
				MemcacheService mc = MemcacheServiceFactory.getMemcacheService();
				List<Entity> news = (List<Entity>) mc.get("news");
				
				// Cold cache.
				if (news == null) {
					DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
					Query query = new Query("News").addSort("date", Query.SortDirection.DESCENDING);
					news = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
					mc.put("news", news);
				}

				if (news.isEmpty()) {
			%>

			<p>Uudiseid veel ei ole.</p>

			<%
				} else {
					int i = 1;
					for (Entity n : news) {
						String title = (String) n.getProperty("title");
						String body = ((Text) n.getProperty("body")).getValue();
						if (i != 1) {
			%>			
			<hr>
			<%
						}
						i++;
			%>
			<h1><%= title %></h1>
			<p><%= body %></p>
			

			<%
					}
				}
			%>
		</div>
		<%
			if (isAdmin) {
		%>
		<div class="content-container">
			<h1>Lisa uudis</h1>
			<form action="/postnews" method="post">
				<table>
					<tr>
						<td>
							<label for="title">Pealkiri: </label>
						</td>
						<td>
							<input id="title" type="text" name="title"></input>
						</td>
					</tr>
					<tr>
						<td>
							<label for="body">Sisu: </label>
						</td>
						<td>
							<textarea id="body" name="body"></textarea>
						</td>
					</tr>
				</table>
				<input type="submit" value="Salvesta"></input>
			</form>
		</div>
		<%
			}
		%>
	</div>
	<%@ include file="footer.jsp"%>
</body>
</html>